$(function() {

	// init date tables
	var dataTable = $("#data_list").dataTable({
		"deferRender": true,
		"processing" : true, 
	    "serverSide": true,
		"ajax": {
			url: base_url + "/jobinfo/pageList",
	        data : function ( d ) {
				var obj = {};
				obj.start = d.start;
				obj.length = d.length;
				obj.name = $('#name').val();
				return obj;
            }
	    },
	    "searching": false,
	    "ordering": false,
	    //"scrollX": true,	// X轴滚动条，取消自适应
	    "columns": [
	                { data: 'sysId', "visible" : true, "width":'5%'},
	                { data: 'name', "width":'10%'},
					{ data: 'createTime', "width":'15%'},
            		{ data: 'modifyTime', "width":'15%'},
            		{ data: 'path', "visible": false},
            		{ data: 'params', "visible": false},
            		{ data: 'range', "visible": false},
            		{ data: 'unit', "visible": false},
            		{ data: 'cron', "visible": true, "width":'8%'},
            		{ data: 'description'},
            		{
                        data: 'content',
                        ordering: true,
                        render : function ( data, type, row ) {
                            if (data) {
                                return '<a href="javascript:;" class="showData" _id="'+ row.sysId +'">查看</spam></a>';
                            } else {
                                return '空';
                            }
                        },
                        "width":'5%'
                    },
                    {
                        data: 'status',
                        render : function ( data, type, row ) {
                            if(data && data != -1) {
                                if(data == 1) {
                                    return '<small class="label label-success" ><i class="fa fa-clock-o"></i>RUNNING</small>';
                                } else {
                                    return '<small class="label label-warning" >ERROR('+data+')</small>';
                                }
                            } else {
                                return '<small class="label label-default" ><i class="fa fa-clock-o"></i>STOP</small>';
                            }

                            return data;
                        },
                        "width":'5%'
                    },
	                { data: 'opt' ,
	                	"render": function ( data, type, row ) {
	                		return function(){

	                			// data
                                tableData['key'+row.sysId] = row;

                                var start_stop = "";

                                if(row.status && row.status != -1) {
                                    if(row.status == 1) {
                                        start_stop = '<button class="btn btn-primary btn-xs job_operate" _type="job_pause" type="button">停止</button>  ';
                                    } else {
                                        start_stop = '<button class="btn btn-primary btn-xs job_operate" _type="job_pause" type="button">停止</button>  ';
                                    }
                                } else {
                                    start_stop = '<button class="btn btn-primary btn-xs job_operate" _type="job_resume" type="button">启动</button>  ';
                                }


                                // opt
	                			var html = '<p id="'+ row.sysId +'" >'+
										'<button class="btn btn-primary btn-xs job_trigger" type="button">执行</button>  '+
										start_stop +
										'<button class="btn btn-warning btn-xs job_modify" type="button">编辑</button>  '+
										'<a href="'+base_url+'/joblog?taskId='+row.sysId+'"><button class="btn btn-info btn-xs job_log" type="button">日志</button></a>  '+
										'<button class="btn btn-danger btn-xs job_operate" _type="job_remove" type="button">删除</button>  '+
								  		'</p>';
	                			return html;
	                		};
	                	},
	                	"width":'15%'
	                }
	            ],
		"language" : {
			"sProcessing" : "处理中...",
			"sLengthMenu" : "每页 _MENU_ 条记录",
			"sZeroRecords" : "没有匹配结果",
			"sInfo" : "第 _PAGE_ 页 ( 总共 _PAGES_ 页 ) 总记录数 _MAX_ ",
			"sInfoEmpty" : "无记录",
			"sInfoFiltered" : "(由 _MAX_ 项结果过滤)",
			"sInfoPostFix" : "",
			"sSearch" : "搜索:",
			"sUrl" : "",
			"sEmptyTable" : "表中数据为空",
			"sLoadingRecords" : "载入中...",
			"sInfoThousands" : ",",
			"oPaginate" : {
				"sFirst" : "首页",
				"sPrevious" : "上页",
				"sNext" : "下页",
				"sLast" : "末页"
			},
			"oAria" : {
				"sSortAscending" : ": 以升序排列此列",
				"sSortDescending" : ": 以降序排列此列"
			}
		}
	});

    // table data
    var tableData = {};

	// msg 弹框
    $("#data_list").on('click', '.showData',function() {
        var _id = $(this).attr('_id');
        var row = tableData['key' + _id ];
        ComAlertTec.show(row.content);
    });

    // search btn
	$('#searchBtn').on('click', function(){
		dataTable.fnDraw();
	});

	////////////////////////////////////////////////////////////////////////////////////////
	//
	// job trigger function
	//
	////////////////////////////////////////////////////////////////////////////////////////
    $("#data_list").on('click', '.job_trigger',function() {
        var id = $(this).parent('p').attr("id");
        var row = tableData['key'+id];

        $("#jobTriggerModal .form input[name='sysId']").val( id );
        $("#jobTriggerModal .form textarea[name='params']").val( row.params );

        $('#jobTriggerModal').modal({backdrop: false, keyboard: false}).modal('show');
    });
    $("#jobTriggerModal .ok").on('click',function() {
        $.ajax({
            type : 'POST',
            url : base_url + "/jobinfo/trigger",
            data : {
                "sysId" : $("#jobTriggerModal .form input[name='sysId']").val(),
                "params" : $("#jobTriggerModal .textarea[name='params']").val()
            },
            dataType : "json",
            success : function(data){
                if (data.code == 200) {
                    $('#jobTriggerModal').modal('hide');

                    layer.msg( data.msg || "执行成功" );
                } else {
                    layer.msg( data.msg || "执行失败" );
                }
            }
        });
    });
    $("#jobTriggerModal").on('hide.bs.modal', function () {
        $("#jobTriggerModal .form")[0].reset();
    });

	
	////////////////////////////////////////////////////////////////////////////////////////
    //
    // job operate function
    //
    ////////////////////////////////////////////////////////////////////////////////////////
	$("#data_list").on('click', '.job_operate',function() {

	    var typeName;
        var url;
        var needFresh = false;

        var type = $(this).attr("_type");
        if ("job_pause" == type) {
            typeName = "停止" ;
            url = base_url + "/jobinfo/stop";
            needFresh = true;
        } else if ("job_resume" == type) {
            typeName = "启动" ;
            url = base_url + "/jobinfo/start";
            needFresh = true;
        } else if ("job_remove" == type) {
            typeName = "删除" ;
            url = base_url + "/jobinfo/remove";
            needFresh = true;
        } else {
            return;
        }

		var id = $(this).parent('p').attr("id");

        layer.confirm( "确认"+typeName+"该JOB文件?", {
            icon: 3,
            title: "系统提示" ,
            btn: [ "确认", "取消" ]
        }, function(index){
            layer.close(index);

            $.ajax({
                type : 'POST',
                url : url,
                data : {
                    "sysId"  : id
                },
                dataType : "json",
                success : function(data){
                    if (data.code == 200) {

                        layer.open({
                            title: "系统提示",
                            btn: [ "确认" ],
                            content: ""+typeName+"成功" ,
                            icon: '1',
                            end: function(layero, index){
                                if(needFresh) {
                                    dataTable.fnDraw(false);
                                }
                            }
                        });
                    } else {
                        layer.open({
                            title: "系统提示",
                            btn: [ "确认" ],
                            content: (data.msg || ""+typeName+"失败" ),
                            icon: '2'
                        });
                    }
                }
            });
        });

	});

	////////////////////////////////////////////////////////////////////////////////////////
    //
    // job add function
    //
    ////////////////////////////////////////////////////////////////////////////////////////
	$('#job_add').on('click', function(){
		$('#addModal').modal({backdrop: false, keyboard: false}).modal('show');
	});
	var addModalValidate = $("#addModal .form").validate({
		errorElement : 'span',
		errorClass : 'help-block',
		focusInvalid : true,
		rules : {
            name : {
                required : true ,
                rangelength:[4,15]
            },
            cron : {
                required : true ,
                rangelength:[6,15]
            },
            description : {
                required : true ,
                rangelength:[4,255]
            },
            content : {
                required : true ,
                rangelength:[4,10000]
            }
		},
		messages : {
            name : {
                required :'请输入'  ,
                rangelength: '长度限制为[4~15]'
            },
            cron : {
                required : '请输入' ,
                rangelength: '长度限制为[6~15]'
            },
            description : {
                required :'请输入'  ,
                rangelength: '长度限制为[4~255]'
            },
            content : {
                required :'请输入'  ,
                rangelength: '长度限制为[4~10000]'
            }
		},
		highlight : function(element) {
			$(element).closest('.form-group').addClass('has-error');
		},
		success : function(label) {
			label.closest('.form-group').removeClass('has-error');
			label.remove();
		},
		errorPlacement : function(error, element) {
			element.parent('div').append(error);
		},
		submitHandler : function(form) {

            // valid
            var name = $("#addModal .form input[name='name']").val();
            var regexpName = new RegExp("^[a-zA-Z0-9_]{4,15}$");
            if (!regexpName.test(name)) {
                layer.open({
                    icon: '2',
                    content: "JOB文件名格式非法，限制为[a-zA-Z0-9_]格式，如 sync_test <br>"
                });
                return;
            }

            var range = $("#addModal .form input[name='range']").val();
            var regexpRange = new RegExp("^-?[0-9]*$");
            if (!regexpRange.test(range)) {
                layer.open({
                    icon: '2',
                    content: "同步范围，只能为数字 <br>"
                });
                return;
            }

            var dataJson = $("#addModal .form textarea[name='content']").val();
            if (dataJson) {
                try {
                    $.parseJSON(dataJson);
                } catch (e) {
                    layer.open({
                        icon: '2',
                        content: "JOB文件内容格式非法，限制为字符串数组JSON格式，如 [address,address2] <br>" + e
                    });
                    return;
                }
            }

            var paramsArr = [];
            $("#addModal .form input[name=params]:checked").each(function(){
                paramsArr.push($(this).val());
            });

            var unit = $("#addModal .form input[name=unit]:checked").val();
            if (unit) {
                if (range == null || range == "" || paramsArr.length == 0) {
                    layer.open({
                        icon: '2',
                        content: "单位不能单独选择，必须与参数名和同步范围组合使用 <br>"
                    });
                    return;
                }

                for(var i = 0; i < paramsArr.length; i ++) {
                    if ((paramsArr[i] == "startId" || paramsArr[i] == "endId") && parseInt(unit) >= 1 && parseInt(unit) < 7) {
                        layer.open({
                            icon: '2',
                            content: "同步范围与单位组合有误，同步范围选择起始与结束id时，单位只能为'none'或'条' <br>"
                        });
                        return;
                    }
                    if ((paramsArr[i] == "startTime" || paramsArr[i] == "endTime") && parseInt(unit) == 7) {
                        layer.open({
                            icon: '2',
                            content: "同步范围与单位组合有误，同步范围选择起始与结束时间时，单位只能为'none'或'年、月、日、时、分、秒' <br>"
                        });
                        return;
                    }
                }
            }


            var paramData = {
                "name": name,
                "range": range,
                "unit": unit,
                "cron": $("#addModal .form input[name=cron]").val(),
                "description": $("#addModal .form input[name=description]").val(),
                "content": dataJson,
                "params": paramsArr.join(',')
            };

            // post
			$.post(base_url + "/jobinfo/add", paramData, function(data, status) {
				if (data.code == "200") {
					$('#addModal').modal('hide');

                    layer.open({
                        title: "系统提示",
                        btn: [ "确认" ],
                        content: "新增成功" ,
                        icon: '1',
                        end: function(layero, index){
                            dataTable.fnDraw(false);
                        }
                    });
				} else {
                    layer.open({
                        title: "系统提示",
                        btn: [ "确认" ],
                        content: (data.msg || "操作失败" ),
                        icon: '2'
                    });
				}
			});
		}
	});
	$("#addModal").on('hide.bs.modal', function () {
		$("#addModal .form")[0].reset();
		addModalValidate.resetForm();
		$("#addModal .form .form-group").removeClass("has-error");
	});

	////////////////////////////////////////////////////////////////////////////////////////
    //
    // job modify function
    //
    ////////////////////////////////////////////////////////////////////////////////////////
	$("#data_list").on('click', '.job_modify',function() {
		var id = $(this).parent('p').attr("id");
        var row = tableData['key' + id ];
        var paramsArr = paramsReplace(row.params);

		$("#modifyModal .form input[name='sysId']").val( id );
		$("#modifyModal .form input[name='name']").val( row.name );
		$("#modifyModal .form input[name='range']").val( row.range );
		$("#modifyModal .form input[name='unit'][value='"+ row.unit +"']").click();
//		$("#modifyModal .form input[name='createTime']").val( row.createTime );
//        $("#modifyModal .form input[name='modifyTime']").val( row.modifyTime );
//        $("#modifyModal .form input[name='path']").val( row.path );

        $("#modifyModal .form input[name='params']").each(function () {
            if($.inArray($(this).val(), paramsArr) > -1) {
                $(this).prop("checked",true);
            } else {
                $(this).prop("checked",false);
            }
        });

//        $("#modifyModal .form input[name='params']").val( row.param );
        $("#modifyModal .form input[name='cron']").val( row.cron );
        $("#modifyModal .form input[name='description']").val( row.description );
        $("#modifyModal .form textarea[name='content']").val( row.content );

		$('#modifyModal').modal({backdrop: false, keyboard: false}).modal('show');
	});
	var paramsReplace = function(params) {

	    var array = params.split(",");
	    var newarray = new Array(array.length);

	    for(var i = 0; i < array.length; i++){
	        newarray[i] = array[i].split("=")[0];
	    }

	    return newarray;
	};
	var modifyModalValidate = $("#modifyModal .form").validate({
		errorElement : 'span',
		errorClass : 'help-block',
		focusInvalid : true,
        rules : {
            name : {
                required : true ,
                rangelength:[4,15]
            },
            cron : {
                required : true ,
                rangelength:[6,15]
            },
            description : {
                required : true ,
                rangelength:[4,255]
            },
            content : {
                required : true ,
                rangelength:[4,10000]
            }
        },
        messages : {
            name : {
                required :'请输入'  ,
                rangelength: '长度限制为[4~15]'
            },
            cron : {
                required : '请输入' ,
                rangelength: '长度限制为[6~15]'
            },
            description : {
                required :'请输入'  ,
                rangelength: '长度限制为[4~255]'
            },
            content : {
                required :'请输入'  ,
                rangelength: '长度限制为[4~10000]'
            }
        },
		highlight : function(element) {
			$(element).closest('.form-group').addClass('has-error');
		},
		success : function(label) {
			label.closest('.form-group').removeClass('has-error');
			label.remove();
		},
		errorPlacement : function(error, element) {
			element.parent('div').append(error);
		},
		submitHandler : function(form) {
            var range = $("#modifyModal .form input[name='range']").val();
            var regexpRange = new RegExp("^-?[0-9]*$");
            if (!regexpRange.test(range)) {
                layer.open({
                    icon: '2',
                    content: "同步范围，只能为数字 <br>"
                });
                return;
            }

            var dataJson = $("#modifyModal .form textarea[name='content']").val();
            if (dataJson) {
                try {
                    $.parseJSON(dataJson);
                } catch (e) {
                    layer.open({
                        icon: '2',
                        content: "JOB文件内容格式非法，限制为字符串数组JSON格式，如 [address,address2] <br>" + e
                    });
                    return;
                }
            }

            var paramsArr = [];
            $("#modifyModal .form input[name=params]:checked").each(function(){
                paramsArr.push($(this).val());
            });

            var unit = $("#modifyModal .form input[name=unit]:checked").val();
            if (unit) {
                if (range == null || range == "" || paramsArr.length == 0) {
                    layer.open({
                        icon: '2',
                        content: "单位不能单独选择，必须与参数名和同步范围组合使用 <br>"
                    });
                    return;
                }

                for(var i = 0; i < paramsArr.length; i ++) {
                    if ((paramsArr[i] == "startId" || paramsArr[i] == "endId") && parseInt(unit) >= 1 && parseInt(unit) < 7) {
                        layer.open({
                            icon: '2',
                            content: "同步范围与单位组合有误，同步范围选择起始与结束id时，单位只能为'none'或'条' <br>"
                        });
                        return;
                    }
                    if ((paramsArr[i] == "startTime" || paramsArr[i] == "endTime") && parseInt(unit) == 7) {
                        layer.open({
                            icon: '2',
                            content: "同步范围与单位组合有误，同步范围选择起始与结束时间时，单位只能为'none'或'年、月、日、时、分、秒' <br>"
                        });
                        return;
                    }
                }
            }


            var paramData = {
                "sysId": $("#modifyModal .form input[name=sysId]").val(),
                "name": $("#modifyModal .form input[name='name']").val(),
                "range": range,
                "unit": unit,
                "cron": $("#modifyModal .form input[name=cron]").val(),
                "description": $("#modifyModal .form input[name=description]").val(),
                "content": dataJson,
                "params": paramsArr.join(',')
            };

            // post
			$.post(base_url + "/jobinfo/modify", paramData, function(data, status) {
				if (data.code == "200") {
					$('#modifyModal').modal('hide');

                    layer.open({
                        title: "系统提示",
                        btn: [ "确认" ],
                        content: "更新成功" ,
                        icon: '1',
                        end: function(layero, index){
                            dataTable.fnDraw(false);
                        }
                    });
				} else {
                    layer.open({
                        title: "系统提示",
                        btn: [ "确认" ],
                        content: (data.msg || "更新失败" ),
                        icon: '2'
                    });
				}
			});
		}
	});
	$("#modifyModal").on('hide.bs.modal', function () {
		$("#modifyModal .form")[0].reset();
		modifyModalValidate.resetForm();
		$("#modifyModal .form .form-group").removeClass("has-error");
	});


});


// Com Alert by Tec theme
var ComAlertTec = {
    html:function(){
        var html =
            '<div class="modal fade" id="ComAlertTec" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">' +
            '<div class="modal-dialog">' +
            '<div class="modal-content-tec">' +
            '<div class="modal-body"><div class="alert" style="color:#fff;"></div></div>' +
            '<div class="modal-footer">' +
            '<div class="text-center" >' +
            '<button type="button" class="btn btn-info ok" data-dismiss="modal" >确认</button>' +
            '</div>' +
            '</div>' +
            '</div>' +
            '</div>' +
            '</div>';
        return html;
    },
    show:function(msg, callback){
        // dom init
        if ($('#ComAlertTec').length == 0){
            $('body').append(ComAlertTec.html());
        }

        // init com alert
        $('#ComAlertTec .alert').html(msg);
        $('#ComAlertTec').modal('show');

        $('#ComAlertTec .ok').click(function(){
            $('#ComAlertTec').modal('hide');
            if(typeof callback == 'function') {
                callback();
            }
        });
    }
};
